﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Net;
using WsusWebAdmin.Web.Wsus;

namespace WsusWebAdmin.Web.Controllers
{
    public class AccountController : BaseController
    {
        //
        // GET: /Account/

        public ActionResult LogOn(string returnUrl)
        {
            ViewData.Model = WsusDataProvider.GetHosts();
            
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(string username, string password, string host, string returnUrl)
        {
            var credentials = new NetworkCredential(username, password);
            bool valid = true;
                       

            var hostData = WsusDataProvider.GetHost(host);

            try
            {
                
                var updateServer = UpdateServerFactory.GetInstance(credentials, hostData);
            }
            catch (Exception e)
            {
                ModelState.AddModelError("_FORM", e.ToString());
                valid = false;
            }

            if (valid)
            {
                Session.Typed().Credentials = credentials;
                Session.Typed().WsusHost = hostData;
                FormsAuthentication.SetAuthCookie(username, false);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ViewData.Model = WsusDataProvider.GetHosts();
                ModelState.AddModelError("_FORM", "Login error");
                return View();
            }
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
    }
}
